import os,datetime,time
from tinydb import TinyDB, Query
from fastapi import FastAPI
from starlette.requests import Request
import os
from fastapi.templating import Jinja2Templates
from starlette.staticfiles import StaticFiles
from starlette.responses import RedirectResponse
from typing import List
from fastapi import FastAPI, File, UploadFile
from starlette.responses import HTMLResponse
import json
import uvicorn
db = TinyDB('db.json')
User = Query()
#db.insert({'name': 'nan1d003', 'software': 'excel','version':'4.2'})

#print(db.search(User.name == 'nan1d-guppjobm1'))
#db.remove(User.name=='John')
#print(sorted(list(set(map(lambda x:x['software'],db)))))
#print(sorted(list(set(map(lambda x:x['name'],db)))))

black_list=['Name',\
        'Sophos',\
        'TelCaPerSTest',\
        'C:\WINDOWS',\
        'C:\Windows',\
        'Microsoft Visual C++',\
        'C:',\
        ' ',\
        ]
def isempty(x):
    if x is '':
        return 0
    else:
        return 1
def action(filename):
    #filename='test.log'
    #print(filename)
    time1=datetime.datetime.today().strftime("%Y-%m-%d %H:%M")
    scan_time=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(os.stat(log).st_mtime))

    with open(filename,'r') as f:
        x=f.readlines()
    new_lines=[]
    for line in x:
        status=0
        for item in black_list:
            if line.isspace():
                status=1
            if line.startswith(item):
                status =1
        if status==0:
            list1=list(filter(lambda x:isempty(x),line.split('  ')))
            #print(filename,line,list1)
            #print(filename.replace('.log',''),list1[0],list1[1].replace('\n','').replace(' ',''),time1)
            db.insert({'name': filename.replace('.log',''), 'software': list1[0],'version':list1[1].replace('\n','').replace(' ',''),'scan_date':scan_time})
            new_lines.append(line)

    #print(new_lines)
    #with open(filename,'w')as f:
    #    f.writelines(new_lines)
    #print(filename+' is done')
db = TinyDB('db.json')
User = Query()
location1='data/'
os.chdir(location1)
dirlist=os.listdir('./')

for log in dirlist:
    print(log)
    if log.endswith('.log'):
        scan_time=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(os.stat(log).st_mtime))
        #print(log,scan_time)
        if db.search(User.name == log.replace('.log',''))==[]:
        #    print('new',log)
            action(log)
        elif db.search(User.name == log.replace('.log',''))[0]['scan_date'] ==scan_time:
            pass
            #print('same')
        elif db.search(User.name == log.replace('.log',''))[0]['scan_date'] <scan_time:
            db.remove(User.name ==log.replace('.log',''))
            #print('diff')
            action(log)
        #pass
#print(db.search(User.name =='nan1d-hpd04'))
db.close()
os.chdir('../')
location='static'
app = FastAPI()
app.mount('/static', StaticFiles(directory=location), name='static') 
#templates = Jinja2Templates(directory="templates")


@app.get("/pc_list")
def root():
    #return {"Hello": "World"}
    db = TinyDB('db.json')
    User = Query()
    #pc_list=sorted(list(set(map(lambda x:x['name'],db))))
    pc_list=list(set(map(lambda x:x['name'],db)))
    pc_list2=list(map(lambda x:[db.search(User.name==x)[0]['name'],db.search(User.name==x)[0]['scan_date']],pc_list))
    #print(pc_list2.sort())
    #pc_list1=[]
    #for pc in pc_list2:
    #    pc_list1.append([pc])
    #pc_list1.sort(reverse = False)
    db.close()
    return HTMLResponse(content=html_head+tab_html('设备清单',['机器名','扫描日期'],pc_list2))


@app.get("/software_list")
def software_list():
    #return {"Hello": "World"}
    db = TinyDB('db.json')
    User = Query()
    pc_list=sorted(list(set(map(lambda x:x['software'],db))))
    print(pc_list)
    pc_list1=[]
    for pc in pc_list:
        pc_list1.append([pc])
    pc_list1.sort(reverse = False)
    db.close()
    return HTMLResponse(content=html_head+tab_html1('软件清单',['机器名'],pc_list1))

@app.get("/software_dir")
def software_dir(request:Request, q: str = None):
    print(q)
    #return {"Hello": "World"}
    db = TinyDB('db.json')
    User = Query()
    #pc_list=sorted(list(set(map(lambda x:x['software'],db))))
    pc_list=db.search(User.name == q)
    #print(pc_list)
    pc_list1=[]
    for pc in pc_list:
        pc_list1.append([pc['name'],pc['software'],pc['version'],pc['scan_date']])
    #pc_list1.sort(reverse = False)
    db.close()
    return HTMLResponse(content=html_head+tab_html0('软件清单',['机器名','软件名','Version','扫描日期'],pc_list1))
@app.get("/software_dir1")
def software_dir1(request:Request, q: str = None):
    print(q)
    #return {"Hello": "World"}
    db = TinyDB('db.json')
    User = Query()
    #pc_list=sorted(list(set(map(lambda x:x['software'],db))))
    pc_list=db.search(User.software == q)
    print(pc_list)
    pc_list1=[]
    for pc in pc_list:
        pc_list1.append([pc['name'],pc['software'],pc['version'],pc['scan_date']])
    #pc_list1.sort(reverse = False)
    db.close()
    return HTMLResponse(content=html_head+tab_html2('软件清单',['机器名','软件名','Version','扫描日期'],pc_list1))
@app.get("/dir")
def read_root():
    #return {"Hello": "World"}
    return RedirectResponse(url='/files/1?q=')


@app.get("/files/{item_id}")
def read_files(request:Request, item_id: str, q: str = None):
    
    #return {"item_id": item_id, "q": q}
    data=['hello','china']
    print('q before:')
    q0=location+'/'+q
    print('q0 after:',q0)
    if os.path.isdir(q0):
        list0=os.listdir(q0)
        print('*****************folder************************'+q0)
    #return x
        return templates.TemplateResponse("dir.html", {"request": request, "id": list0, "id1":"xxxx", "q":q})
    else:
        print('&&&&&&&&&&&file&&&&&&&&&&&&&&&&&&&&&&'+q0)
        q=q.replace(' ','%20')
        print('q again:::::::',q)
        return RedirectResponse(url='/static'+q)
    
def tab_html(title,headers0,rows):
    start='''
    <table class="table table-condensed">
        <thead>
            <tr>
                <th>#</th>
                <th>Firstname</th>
                <th>2nname</th>
            </tr>
        </thead>
        '''
    headers='<body><h2>'+title+'</h2><table class="table table-bordered table-striped"><thead><tr>'
    for item in headers0:
        headers=headers+'<th>'+item+'</th>'
    headers=headers+'</tr></thead>'
    body='<tbody>'
    i=1
    for item in rows:
        body=body+'<tr>'
        i0=0
        for x in item:
            if i0==0:
                body=body+'<td><a href="{}?q={}">{}</a>'.format('software_dir',str(x),str(x))+'</td>'
            else:
                body=body+'<td>{}'.format(str(x))+'</td>'
            i0=i0+1
        i=i+1
        body=body+'</tr>'
    body=body+'</tbody></table></body>'
    return headers+body

def tab_html0(title,headers0,rows):
    start='''
    <table class="table table-condensed">
        <thead>
            <tr>
                <th>#</th>
                <th>Firstname</th>
                <th>2nname</th>
            </tr>
        </thead>
        '''
    headers='<body><h2>'+title+'</h2><table class="table table-bordered table-striped"><thead><tr>'
    for item in headers0:
        headers=headers+'<th>'+item+'</th>'
    headers=headers+'</tr></thead>'
    body='<tbody>'
    i=1
    for item in rows:
        body=body+'<tr>'
        i0=0
        for x in item:
            if i0==1:
                body=body+'<td><a href="{}?q={}">{}</a>'.format('software_dir1',str(x),str(x))+'</td>'
            else:
                body=body+'<td>{}'.format(str(x))+'</td>'
            i0=i0+1
        i=i+1
        body=body+'</tr>'
    body=body+'</tbody></table></body>'
    return headers+body

def tab_html1(title,headers0,rows):
    start='''
    <table class="table table-condensed">
        <thead>
            <tr>
                <th>#</th>
                <th>Firstname</th>
                <th>2nname</th>
            </tr>
        </thead>
        '''
    headers='<body><h2>'+title+'</h2><table class="table table-bordered table-striped"><thead><tr>'
    for item in headers0:
        headers=headers+'<th>'+item+'</th>'
    headers=headers+'</tr></thead>'
    body='<tbody>'
    i=1
    for item in rows:
        body=body+'<tr>'
        i0=0
        for x in item:
            if i0==0:
                body=body+'<td><a href="{}?q={}">{}</a>'.format('software_dir1',str(x),str(x))+'</td>'
            else:
                body=body+'<td>{}'.format(str(x))+'</td>'
            i0=i0+1
        i=i+1
        body=body+'</tr>'
    body=body+'</tbody></table></body>'
    return headers+body

def tab_html2(title,headers0,rows):
    start='''
    <table class="table table-condensed">
        <thead>
            <tr>
                <th>#</th>
                <th>Firstname</th>
                <th>2nname</th>
            </tr>
        </thead>
        '''
    headers='<body><h2>'+title+'</h2><table class="table table-bordered table-striped"><thead><tr>'
    for item in headers0:
        headers=headers+'<th>'+item+'</th>'
    headers=headers+'</tr></thead>'
    body='<tbody>'
    i=1
    for item in rows:
        body=body+'<tr>'
        i0=0
        for x in item:
            if i0==0:
                body=body+'<td><a href="{}?q={}">{}</a>'.format('software_dir',str(x),str(x))+'</td>'
            else:
                body=body+'<td>{}'.format(str(x))+'</td>'
            i0=i0+1
        i=i+1
        body=body+'</tr>'
    body=body+'</tbody></table></body>'
    return headers+body

#html头部
html_head='''

<html>

  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 上述3个meta标签*必须*放在最前面，任何其他内容都*必须*跟随其后！ -->
    <title>Bootstrap 101 Template</title>

    <!-- Bootstrap -->
    <link rel="stylesheet" href="/static/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">

    <!-- HTML5 shim 和 Respond.js 是为了让 IE8 支持 HTML5 元素和媒体查询（media queries）功能 -->
    <!-- 警告：通过 file:// 协议（就是直接将 html 页面拖拽到浏览器中）访问页面时 Respond.js 不起作用 -->
    <!--[if lt IE 9]>
      <script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
    <![endif]-->
  </head>

<body>
'''
#默认主目录
@app.get("/")
def main():
    return HTMLResponse(content='<br><a href="pc_list">设备清单</a></br><br><a href="software_list">软件清单</a></br>')
    return RedirectResponse(url='/pc_list')

if __name__ == "__main__":

    
    #指定fastapi的运行端口
    uvicorn.run(app, host="0.0.0.0",port=80,log_level="info")
    print('hello')

